import { BasicDrawer, useDrawerInner } from "@/components/Drawer";
import { BasicForm, FormSchema, useForm } from "@/components/Form";
import { AccountApi } from "@/api/erp/finance/account";
// import { drugCategoryApi } from "@/api/erp/drug/category";
import { message } from "antd";
import { useTranslation } from "react-i18next";
import { useState, useMemo } from "react";
let reload: Function;
let id: string;

const index = (props: { register: Fn }) => {
	const [isUpdated, setIsUpdated] = useState(false);
	const { t } = useTranslation();
	const en_vi1 = "drugStorage.inventoryManagement.warehouseInformation";
	const en_vi = "drugStorage.financialManagement.settlementAccount";
	const formSchema: FormSchema[] = [
		{
			label: t(`${en_vi}.name`),
			field: "name",
			component: "Input"
		},
		{
			label: t(`${en_vi}.code`),
			field: "no",
			component: "Input"
		},
		{
			label: t(`${en_vi}.remark`),
			field: "remark",
			component: "InputTextArea"
		},
		{
			label: t(`${en_vi}.sort`),
			field: "sort",
			component: "InputNumber"
		},
		{
			label: t("felix_ui.status"),
			field: "status",
			component: "RadioGroup",
			componentProps: {
				options: [
					{ label: t(`drugStorage.inventoryManagement.warehouseInformation.open`), value: 0 },
					{ label: t(`drugStorage.inventoryManagement.warehouseInformation.close`), value: 1 }
				]
			}
		}
	];
	const getTitle = useMemo(() => {
		return isUpdated ? t(`${en_vi1}.editWarehouseInfo`) : t(`${en_vi1}.addWarehouseInfo`);
	}, [isUpdated]);
	const [register, { validateFields, setFieldsValue, resetFields }] = useForm({
		schemas: formSchema,
		labelWidth: 120,
		baseColProps: {
			span: 24
		}
	});
	const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(props.register, data => {
		reload = data.reload;
		id = data.record?.id;
		resetFields();
		setDrawerProps({ confirmLoading: true });
		setIsUpdated(!!data?.isUpdated);
		setFieldsValue({
			...data.record
		});
		setDrawerProps({ confirmLoading: false });
	});
	const handleSubmit = async () => {
		const formValue = await validateFields();
		let res;
		if (isUpdated) {
			formValue.id = id;
			res = await AccountApi.updateAccount(formValue);
		} else {
			res = await AccountApi.createAccount(formValue);
		}
		if (!res) {
			message.error(t("viewComponents.patientInformation.additionFailed"));
			return;
		}
		message.success(t("viewComponents.patientInformation.successfullyAdded"));
		closeDrawer();
		reload();
	};
	return (
		<BasicDrawer title={getTitle} showFooter={true} {...props} register={registerDrawer} ok={handleSubmit}>
			<BasicForm register={register} labelWrap={true}></BasicForm>
		</BasicDrawer>
	);
};
export default index;
